package com.demo.my.Dao;

import com.demo.my.Entity.Position;
import com.demo.my.Util.BaseDAO;
import com.demo.my.Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class PositionDao extends BaseDAO{
    private static BaseDAO dao = new BaseDAO() ;
    public  Position getEntityById(Integer id) {
        String sql = "select * from position where positionNumber=?";
        Object[] objs = {id};
        try {
            Position one = dao.getOne(sql, new Position(), objs);
            return one;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Position> getPositionList() throws Exception {
        String sql="select * from position";
        Object[]obj={};
        return getList(sql,new Position(),obj);
    }

    public void addPosition(Position position) throws Exception {
        String sql="insert into position values(null,?,?,?,?)";
        Object[]obj={position.getPositionNumber(),position.getName(),position.getLevel(),
        position.getNotes()};
        addOrupdOrdel(sql,obj);
    }

    public Position getPositionByid(String id) throws Exception {
        String sql="select * from position where id=?";
        Object[]obj={id};
        Position position = getOne(sql, new Position(), obj);
        return position;
    }

    public void updatePosition(Position position) throws Exception {
        String sql="update position set positionNumber=?,name=?,level=?,notes=? where id=?";
        Object[]obj={position.getPositionNumber(),position.getName(),position.getLevel(),
                position.getNotes(),position.getId()};
        addOrupdOrdel(sql,obj);
    }

    public void deleteByid(String id) throws Exception {
        String sql="delete from position where id=?";
        Object[]obj={id};
        addOrupdOrdel(sql,obj);
    }

    public Position getPositionByNumber(int positionNumber) throws Exception {
        String sql="select * from position where positionNumber=?";
        Position position = getOne(sql, new Position(), positionNumber);
        return position;
    }
    public int getMaxNumber() throws SQLException {
        Connection conn = DBUtil.getConnection();
        String sql="select max(positionNumber) from position";
        PreparedStatement st = conn.prepareStatement(sql);
        ResultSet rs = st.executeQuery();
        rs.next();
        int maxNumber = rs.getInt(1);
        DBUtil.close(rs,st,conn);
        return maxNumber;
    }
}
